/*
 *
 */
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery','easydrag'], factory);
    } else {
        factory(window.jQuery);
    }
}(function(a) {
    var css='./filemanager/ui.css';
    css = require[require.toUrl ? 'toUrl' : 'resolve'](css);
    css = '<link rel="stylesheet" href="' + css + '" />';
    if (a('base')[0]) {
        a('base').before(css);
    } else {
        a('head').append(css);
    }
    a.fn.filemanager = function(o, callback) {
        var defaults = {
            width:650,
            pagenum:18,
            max:1,
			input_field:'',
			file_dir:'',
			order_id:'',
			file_uid:'',
            json : FILEHOST+'/file_manager_json.php'
        };
        
        return this.each(function() {
			var c = a.extend({}, defaults, o);
            var t = a(this);
            c.input_field= o.input ? o.input : t.parent().siblings('.input_field').val();
            c.max = o.max ? o.max : t.parent().siblings('.maxNum').val();
            c.file_dir = o.path ? o.path : t.parent().siblings('.upload_path').val();
            c.file_uid = t.parent().siblings('.upload_uid').val();

            var b={
                dialog:a('.j-dialog'),
                body:null,
                bg:null,
                close:null,
                area:null,
                page:null
            },
            d={
                moveup:'',
                current_dir:'',
                loading:'<div class="j-dialog-loading"><div class="j-inline-block j-dialog-loading-content">加载中，请稍候 ...</div></div>',
                template:'<div class="j-dialog">'
                        +'<div class="j-dialog-content">'
                            +'<div class="j-dialog-header" id="j-dialog-header">文件空间<span title="关闭" class="j-dialog-icon-close"></span></div>'
                            +'<div class="j-dialog-body">'
                                +'<div style="padding:10px 20px;">'
                                    +'<div class="j-plugin-filemanager-header">'
                                        //+'<div class="j-left"><i class="moveup j-inline-block"></i> <a href="javascript:;" name="moveupLink" class="j-inline-block">移到上一级文件夹</a></div>'
                                        +'<div class="j-right">'
                                            +'显示方式： <select name="viewType" class="j-inline-block"><option value="VIEW">缩略图</option><option value="LIST">详细信息</option></select> '
                                            +'排序方式： <select name="orderType" class="j-inline-block"><option value="NAME">名称</option><option value="SIZE">大小</option><option value="TYPE">类型</option></select>'
                                        +'</div>'
                                        +'<div class="j-clearfix"></div>'
                                    +'</div>'
                                    +'<div class="j-plugin-filemanager-body"></div>'
                                +'</div>'
                            +'</div>'
                            +'<div class="j-dialog-footer"><div class="j-dialog-page"></div><div class="j-button-common"></div></div>'
                        +'</div>'
                        +'<div class="j-dialog-shadow"></div>'
                    +'</div><div class="j-dialog-mask"></div>',
                item:'<div class="j-inline-block j-item">'
                        +'<div class="j-inline-block j-photo" style="cursor: pointer;"></div>'
                        +'<div class="j-name"></div>'
                    +'</div>',                
                init:function(){
                    //拖拽
                    b.dialog.easydrag();
                    b.dialog.setHandler("j-dialog-header");
                    //关闭
                    b.close.click(function(){
                        d.close();
                    });
                    if(c.max>1){
                        var btnok=a('<a href="javascript:;" data-id="ok">确定</a>'); 
                        b.dialog.find('.j-button-common').append(btnok);
                        btnok.on('click',function(){
                            var data=[];
                            var box=$(t).parent().parent('._upfile');
                            if(b.area.find('.selected').length) {
                                box.children('.upload-area').html('');
                                b.area.find('.selected').each(function () {
                                    var imgdata = a(this).data('img');
                                    data.push(imgdata[1]);

                                    var file_html = '<div class="f-item"><img src="' + imgdata[0] + '" img_name="' + imgdata[1] + '"><span></span><i title="删除该图片"></i><input type="hidden" value="' + imgdata[1] + '" name="' + c.input_field + '[]"></div>';
//                                    $(t).parent().parent('._upfile').children('.upload-area').append(file_html);
                                    $(t).parent().parent('._upfile').children('div:last').append(file_html);
                                });
                                a(c.input).val(data.join(','));
                            }

                            if(box.find('.f-item').length>=c.max && c.max>1){
                                box.find('.fileupload').hide().prop("disabled",true);
                            }else{
                                box.find('.fileupload').show().prop("disabled",false);
                            }
                            d.close();
                        });
                    };
                    //上一目录
                    b.dialog.find('[name="moveupLink"]').click(function(){
                        d.loadings(d.moveup,1);
                    });
                    //显示方式,排序
                    b.dialog.find('select[name="viewType"],select[name="orderType"]').change(function(){
                        d.loadings();
                    });
                    d.loadings();
                },
                loadings:function(path,up){
                    var l=a(d.loading);
                    a(b.body).after(l);
                    l.css({width: b.body.width()+'px', height:b.body.height()+'px', top: 25+'px'});
                    l.find('.j-dialog-loading-content').css({marginTop:b.body.height()/2});
                    //url地址
                    var url=[];
                    url.push('path='+(path?(up?path.replace('/','%2F'):(d.current_dir+''+path+'/').replace('/','%2F')):''));
                    url.push('dir='+c['file_dir']);
//					url.push('order_id='+c['order_id']);
					url.push('file_uid='+c['file_uid']);
                    url.push('order='+b.dialog.find('select[name="orderType"]').val());

                    a.get(c.json+'?'+url.join('&'),function(data){
                        l.remove();

                        d.moveup=data.moveup_dir_path;
                        d.current_dir=data.current_dir_path;
                        
                        d.data=data;
                        if(data.total_count){
                            d.setpage();
                            d.getpage(0);
                        }else{
                            b.area.html('<div>没有数据</div>');
                        }
                    },'jsonp');
                },
                setpage:function(){
                    var data=d.data;
                    var totalp=0;
                    if(data.total_count % c.pagenum){
                        totalp=parseInt(data.total_count / c.pagenum)+1;
                    }else{
                        totalp=parseInt(data.total_count / c.pagenum);
                    }
                    b.page.html('');
                    if(totalp<2){
                        return false;
                    }
                    for(var i=0;i<totalp;i++){
                        var p=a('<a href="javascript:;">'+(i+1)+'</a>');
                        b.page.append(p);
                        p.click(function(){
                            a(this).addClass('active').siblings().removeClass('active');
                            d.getpage(parseInt(a(this).html())-1);
                        });
                    }
                    if(totalp>10){
                        var select=$('<select/>');
                        for(var i=0;i<totalp;i++){
                            select.append('<option value="'+(i+1)+'">'+(i+1)+'</option>');                            
                        }
                        select.change(function(){
                            d.getpage(parseInt(a(this).val())-1);
                        });
                        b.page.append(select);
                    }
                },
                getpage:function(p){
                    b.area.html('');
                    var data=d.data;
                    var fpath=data.current_url;
                    var area=b.area;
                    if(b.dialog.find('select[name="viewType"]').val()=='LIST'){
                        b.area.append('<table cellspacing="0" cellpadding="0" border="0" class="j-table"></table>');
                        area=b.area.find('table');
                    }
                    var min=parseInt(p)*parseInt(c.pagenum);
                    var max=(p*c.pagenum+c.pagenum)>data.total_count?data.total_count:p*c.pagenum+c.pagenum;
                    
                    for(var i=min;i<max;i++){
                        var j=data.file_list[i];
                        var filename=j.filename;

						if(j.filetype=='rar'){
							filename = './filemanager/rar.png'; 
						}else if(j.filetype=='pdf'){
							filename = './filemanager/pdf.png';
						}

                        filesize=Math.ceil(j.filesize/1024)+'KB';
                        if(b.dialog.find('select[name="viewType"]').val()=='LIST'){
                            j.is_dir && (file=d.getfile('./filemanager/folder.png')) || (file=d.getfile('./filemanager/file-16.gif'));
                            item='<tr style="cursor: pointer;">'
                                    +'<td class="j-cell j-name" title="'+filename+'"><img width="16" height="16" align="absmiddle" alt="'+filename+'" src="'+file+'"> '+filename+'</td>'
                                    +'<td class="j-cell j-size">'+filesize+'</td>'
                                    +'<td class="j-cell j-datetime">'+j.datetime+'</td>'
                                    +'</tr>';
                            var item=a(item);
                            !j.is_dir && item.data('img',[j.full_name,j.filename])
                        }else{
                            //20150112修改
                            if(('.'+ j.filetype).isImg()){
                                var fileSrc = fpath+filename;
                            } else {
                                var fileSrc = PUBLIC + '/admin/images/txt.gif';
                                j.full_name = fileSrc;
                            }

                            var item=a(d.item);
                            j.is_dir?(
                               file=d.getfile('./filemanager/folder.png'),
                               item.find('.j-photo').html('<img width="80" height="80" src="'+file+'">')
                            ):(
                               item.find('.j-photo').html('<img width="80" height="80" alt="'+filename+'" src="'+fileSrc+'">'),item.data('img',[j.full_name,j.filename])
                                ,item.find('.j-photo').append('<i class="del"></i>')
                            );
                            item.data('is_dir',j.is_dir)
                            item.find('.j-photo').attr('title',filename+' ('+filesize+', '+j.datetime+')');
                            item.find('.j-name').html(filename).attr('title',filename);
                        }
                        item.find('.del').click(function(){
                            if(confirm('确认是否删除该文件！')){
                                var li=a(this).closest('.j-item');
                                var imgdata=li.data('img');
                                var img = imgdata[1];
                                $.getJSON(FILEHOST+"?do=delete&do_type="+c['file_dir']+"&operator=user&filepaths="+img+"&callback=?",function(data){
                                    li.fadeOut(function(){
                                        $(this).remove();
                                    });
                                });
                            }
                            return false;
                        });
                        item.hover(function(){
                            a(this).find('.j-photo').addClass('hover');
                        },function(){
                            a(this).find('.j-photo').removeClass('hover');
                        }).click(function(){
                            if(a(this).data('is_dir')){
                                d.loadings(a(this).find('.j-name').attr('title'));
                            }else{
                                if(c.max ==1){
                                    var imgdata=a(this).data('img');
                                    a(c.input).val(a(this).find('.j-name').attr('title'));


                                    var file_html = '<div class="f-item"><img src="'+imgdata[0]+'" img_name="'+imgdata[1]+'"><span></span><i title="删除该图片"></i><input type="hidden" value="'+imgdata[1]+'" name="'+c.input_field+'[]"></div>';
//                                    $(t).parent().parent('._upfile').children('.upload-area').html(file_html);
                                    $(t).parent().parent('._upfile').children('div:last').html(file_html);
                                    d.close();
                                    if($.isFunction(c['fn'])){ c['fn'](imgdata[0],imgdata[1],c['input_field']);}
                                }else{
                                    var lens=a(this).siblings('.selected').length;
                                    if(lens >= c.max){
                                        alert('最多可选择：'+c.max+' 项');
                                    }else{
                                        a(this).toggleClass('selected');
                                    }
                                };
                            }
                        });
                        area.append(item);
                    };
                },
                close:function(){
                    b.dialog.remove();
                    b.bg.remove();
                },
                getfile:function(file){
                    return require[require.toUrl ? 'toUrl' : 'resolve'](file);
                }
            },
            g = function() {
                var w = a(window).width(),h = a(window).height()>a('body').height()?a(window).height():a('body').height();
                b.bg.css({width:w,height:h,zIndex:88888});
            };
            t.click(function(){
                a('body').append(d.template),
                b.dialog=a('.j-dialog');
                b.body=b.dialog.find('.j-dialog-body'),
                b.bg=a('.j-dialog-mask'),
                b.close=b.dialog.find('.j-dialog-icon-close,.j-dialog-no'),
                b.area=b.dialog.find('.j-plugin-filemanager-body'),
                b.page=b.dialog.find('.j-dialog-page');

                var left = a(window).scrollLeft() + ((a(window).width()-c.width) / 2),
                    top = a(window).scrollTop() + ((a(window).height()-b.dialog.height()) / 2);
                left=left<0?10:left;
                top =top<0?10:top;
                b.dialog.css({left:left,top:top,width:c.width+'px',zIndex:88889});
                
                d.init();
                g();             
                a(window).on("resize", g);
            });
        });
    };
}));